package com.itheima.controller;

import com.itheima.upload.UploadUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("upload")
public class UploadController {

    @RequestMapping("upload-file")
    public String uploadFile(@RequestParam("upload") MultipartFile file){
        // 向某个tomcat服务器上传文件时,需要修改该tomcat的只读属性为false,不然会报 403 Forbidden：资源不可用。服务器理解客户的请求，但拒绝处理它。通常由于服务器上文件或目录的权限设置导致。
        // 在 conf/web.xml  的 DefaultServlet里配置一下参数
        // <init-param>
        //   <param-name>readonly</param-name>
        //   <param-value>false</param-value>
        //</init-param>

        try {
            String originalFilename = file.getOriginalFilename();
            String uuidFileName = UploadUtils.generateRandonFileName(originalFilename);
            //   上传 。。。本地磁盘  ----jersey  -----9001 服务器上
            Client client = new Client();//  获取jersey客户端对象
            WebResource resource = client.resource("http://127.0.0.1:8080/upload/"+uuidFileName);
            resource.put(file.getBytes());//  put方法文件内容 传输远程 服务器上
            return "redirect:/upload/success.html";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/upload/error.html";
        }
    }
}
